package com.tencent.cloud.iov.util;

import android.text.TextUtils;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA256工具类
 *
 * @author vinsonhuang
 * @date 2018/5/18
 */
public class SHAUtils {

    private static final String TAG = SHAUtils.class.getSimpleName();

    private static final String ALGORITHM = "SHA-256";

    private static final char[] HEX_CODE = "0123456789ABCDEF".toCharArray();

    /**
     * 计算字节数组 sha256 值
     *
     * @param bytes
     * @return
     */
    public static String sha256OfBytes(byte[] bytes) {
        if (null == bytes) {
            return "";
        }
        try {
            // SHA 加密开始
            // 创建加密对象 并传入加密类型
            MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
            // 传入要加密的字符串
            messageDigest.update(bytes);
            // 得到 byte 类型结果
            byte[] byteBuffer = messageDigest.digest();
            return transBytesToHexString(byteBuffer);
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "compute sha256 failed", e);
        }

        return "";
    }

    /**
     * 计算文件 sha256 值
     *
     * @param filePath
     * @return
     */
    public static String sha256OfFile(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return "";
        }

        byte[] byteArray = null;


        File file = new File(filePath);
        if (!file.isFile()) {
            return "";
        }

        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            int len;
            while ((len = fis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            byteArray = outputStream.toByteArray();
        } catch (IOException e) {
            Log.e(TAG, "read file content failed", e);
        }

        if (null == byteArray) {
            return "";
        }
        return sha256OfBytes(byteArray);
    }

    /**
     * 计算字符串 sha256 值
     *
     * @param data
     * @return
     */
    public static String sha256OfString(String data) {
        if (TextUtils.isEmpty(data)) {
            return "";
        }
        return sha256OfBytes(data.getBytes());
    }

    /**
     * 将字节数组转换为16进制字符串
     *
     * @param data
     * @return
     */
    public static String transBytesToHexString(byte[] data) {
        if (null == data || 0 == data.length) {
            return "";
        }
        StringBuilder hexStr = new StringBuilder(data.length * 2);
        for (byte b : data) {
            hexStr.append(HEX_CODE[(b >> 4) & 0xF]);
            hexStr.append(HEX_CODE[(b & 0xF)]);
        }
        return hexStr.toString();
    }
}
